# -*- coding: utf-8 -*-
"""
数据库初始数据插入
"""

import logging
from sqlalchemy.exc import IntegrityError

from config.settings import TARGET_CITIES, TARGET_BUSINESS_TYPES
from .models import City, BusinessType
from .connection import db_manager

logger = logging.getLogger(__name__)


def insert_initial_data():
    """插入初始配置数据"""
    try:
        with db_manager.get_session() as session:
            # 插入城市数据
            insert_cities(session)
            
            # 插入业态数据
            insert_business_types(session)
            
        logger.info("初始数据插入完成")
    except Exception as e:
        logger.error(f"初始数据插入失败: {e}")
        raise


def insert_cities(session):
    """插入城市配置数据"""
    for city_config in TARGET_CITIES:
        try:
            # 检查是否已存在
            existing_city = session.query(City).filter_by(
                city_name=city_config['name']
            ).first()
            
            if not existing_city:
                city = City(
                    city_name=city_config['name'],
                    city_code=city_config['code'],
                    is_active=True
                )
                session.add(city)
                logger.info(f"插入城市: {city_config['name']}")
            else:
                logger.info(f"城市已存在: {city_config['name']}")
                
        except IntegrityError as e:
            logger.warning(f"城市数据插入冲突: {city_config['name']} - {e}")
            session.rollback()


def insert_business_types(session):
    """插入业态配置数据"""
    for business_config in TARGET_BUSINESS_TYPES:
        try:
            # 检查是否已存在
            existing_type = session.query(BusinessType).filter_by(
                type_name=business_config['name']
            ).first()
            
            if not existing_type:
                business_type = BusinessType(
                    type_name=business_config['name'],
                    type_code=business_config['code'],
                    is_active=True
                )
                session.add(business_type)
                logger.info(f"插入业态: {business_config['name']}")
            else:
                logger.info(f"业态已存在: {business_config['name']}")
                
        except IntegrityError as e:
            logger.warning(f"业态数据插入冲突: {business_config['name']} - {e}")
            session.rollback()


def get_city_by_name(session, city_name: str) -> City:
    """根据城市名称获取城市对象"""
    return session.query(City).filter_by(city_name=city_name).first()


def get_business_type_by_name(session, type_name: str) -> BusinessType:
    """根据业态名称获取业态对象"""
    return session.query(BusinessType).filter_by(type_name=type_name).first()


def get_all_active_cities(session):
    """获取所有启用的城市"""
    return session.query(City).filter_by(is_active=True).all()


def get_all_active_business_types(session):
    """获取所有启用的业态"""
    return session.query(BusinessType).filter_by(is_active=True).all()


if __name__ == "__main__":
    # 设置日志
    logging.basicConfig(level=logging.INFO)
    
    # 插入初始数据
    insert_initial_data()
